package com.example.shengyin.util;


import java.awt.*;
import java.awt.image.BufferedImage;
        import java.io.File;
        import java.io.IOException;
import java.util.UUID;
import javax.imageio.ImageIO;

public class ImgCom {
    public static String yasuo(String path,String imgpath, String houzhui) {
        try {
            // 读取原始图片
            String imgname= UUID.randomUUID() +"."+ houzhui;
            File inputFile = new File(path+"/"+imgpath);
            BufferedImage inputImage = ImageIO.read(inputFile);

            // 获取图片的宽度和高度
            int width = inputImage.getWidth();
            int height = inputImage.getHeight();

            // 创建一个新的BufferedImage对象，指定压缩后的图片质量
            BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 创建一个Graphics2D对象并设置压缩质量
            float scaleFactor = 1f; // 压缩比例，可以根据需要调整
            while (width * height * scaleFactor > 50000) {
                scaleFactor -= 0.1;
            }

            int quality = (int) (scaleFactor * 100); // 将压缩比例转换为质量值（百分比）
            Graphics2D g2d = outputImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            // 将原始图像绘制到输出图像上，并实现压缩效果
            g2d.drawImage(inputImage, 0, 0, width, height, null);
            g2d.dispose();

            // 将压缩后的图片写入文件
            File outputFile = new File(path+"/"+imgname);
            ImageIO.write(outputImage, houzhui, outputFile);
            return imgname;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
